package cn.com.pc.content.util;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.sql.*;
import java.util.Properties;

@Component
public class OJDBCUtils {

    private static String url;
    private static String user;
    private static String password;
    private static String driver;

    @Value("${ojdbc.datasource.url}")
    private void setUrl(String value) {
        url = value;
    }

    @Value("${ojdbc.datasource.user}")
    private void setUser(String value) {
        user = value;
    }

    @Value("${ojdbc.datasource.password}")
    private void setPassword(String value) {
        password = value;
    }

    @Value(value = "${ojdbc.datasource.driver}")
    private void setdriver(String value) {
        driver = value;
    }

    /**
     * 获取连接对象
     *
     * @return 连接对象
     */
    public static Connection getConnection() {
        try {
            Class.forName(driver);
            Properties props = new Properties();
            props.put("user", user);
            props.put("password", password);
            props.put("oracle.net.CONNECT_TIMEOUT", "10000000");
            return DriverManager.getConnection(url, props);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("获取oracle连接失败");
        }
    }

    public static void close(ResultSet rs, Statement stmt,Connection conn) {
        try {
            if (rs != null) {
                rs.close();
            }
            if (stmt != null) {
                stmt.close();
            }
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException("关闭oracle连接失败");
        }
    }

    public static void close(ResultSet rs, Statement stmt) {
        close(rs , stmt, null);
    }

    public static void close(Statement stmt, Connection conn) {
        close(null , stmt, conn);
    }
}
